<template>
  <Form ref='fm' v-slot='{errors}' :validation-schema="mySchema" class="xtx-form">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{error:errors.account}" name='account' v-model="formData.account" class="input" type="text" placeholder="请输入用户名" />
      </div>
       <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.account">
        <i class="iconfont icon-warning" />{{ errors.account }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{error:errors.mobile}" name='mobile' v-model="formData.mobile" class="input" type="text" placeholder="请输入手机号" />
      </div>
        <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.mobile">
        <i class="iconfont icon-warning" />{{ errors.mobile }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{error:errors.code}" name='code' v-model="formData.code" class="input" type="text" placeholder="请输入验证码" />
        <span @click="handlerCode" class="code">{{count===0?'发送验证码':`${count}秒后发送`}}</span>
      </div>
       <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.code">
        <i class="iconfont icon-warning" />{{ errors.code }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{error:errors.password}" name='password' v-model="formData.password" class="input" type="password" placeholder="请输入密码" />
      </div>
       <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.password">
        <i class="iconfont icon-warning" />{{ errors.password }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{error:errors.rePassword}" name='rePassword' v-model="formData.rePassword" class="input" type="password" placeholder="请确认密码" />
      </div>
       <!-- 表单验证错误信息提示 -->
      <div class="error" v-show="errors.rePassword">
        <i class="iconfont icon-warning" />{{ errors.rePassword }}
      </div>
    </div>
    <a @click="bindQQ" href="javascript:;" class="submit">立即提交</a>
  </Form>
</template>

<script>
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'

import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'

import { userQQPatchCode, userQQPatchLogin } from '@/api/user'

import { useCountDown } from '@/hooks'

import { message } from '@/components/Message/index.js'

// 表单校验
const validateForm = () => {
  const formData = reactive({
    account: null,
    mobile: null,
    code: null,
    password: null,
    rePassword: null
  })

  const mySchema = {
    account: schema.accountApi,
    mobile: schema.mobile,
    code: schema.code,
    password: schema.password,
    rePassword: schema.rePassword
  }
  return { formData, mySchema }
}

// 点击发送验证码
const useSendCode = (formData) => {
  // 获取组件表单实例
  const fm = ref()

  // 调用倒计时方法
  const { count, start } = useCountDown(60)

  // 点击发送事件
  // 手机号格式正确才能发送点击事件发送验证码
  const handlerCode = async () => {
    // 手动校验表单某一项
    const validate = schema.mobile(formData.mobile)

    if (validate === true) {
    // 根据count是否为0,判断是否发送验证码
      if (count.value === 0) {
        try {
          await userQQPatchCode(formData.mobile)
          message({ type: 'success', text: '发送成功' })
          start()
        } catch (error) {
          message({ type: 'error', text: error.response.data.message })
        }
      }
    } else {
      // 手机号码格式错误
      // 根据组件表单实例js 触发显示错误信息
      fm.value.setFieldError('mobile', validate)
    }
  }

  return { handlerCode, fm, count }
}

// 注册小兔子账号并绑定qq号
const useSubmit = (fm, props, formData) => {
  const store = useStore()
  const router = useRouter()
  const route = useRoute()

  // 点击绑定事件
  const bindQQ = async () => {
    // 整体校验
    // 绑定
    // 成功，回跳
    const res = await fm.value.validate()
    if (res.valid) {
      try {
        const { result } = await userQQPatchLogin({
          unionId: props.unionId,
          ...formData
        })
        // 登陆成功存储用户信息
        await store.commit('user/setProfile', result)
        // 是否带有401的页面
        router.replace(route.query.redirect || '/')
        message({ type: 'success', text: '注册小兔子并绑定成功' })
      } catch (error) {
        message({ type: 'error', text: '注册小兔子并绑定失败' })
      }
    }
  }

  return { bindQQ }
}

export default {
  name: 'CallbackPatch',

  components: {
    Form, Field
  },

  props: {
    unionId: {
      type: String,
      default: ''
    }
  },

  setup (props) {
    const { formData, mySchema } = validateForm()

    const { handlerCode, fm, count } = useSendCode(formData)

    const { bindQQ } = useSubmit(fm, props, formData)

    return { formData, mySchema, handlerCode, fm, count, bindQQ }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
